<template>
  <el-main style="background-color: white">
    <el-table
      height="70vh"
      :data="formedData"
      v-loading="isLoading"
      element-loading-background="rgba(255, 255, 255, 1)"
      style="max-height: 70vh"
    >
      <el-table-column
      prop="index"
      label="指标"
      min-width="140px"
      property ="index"
      align="center"
      header-align="center"
      ></el-table-column>
      <el-table-column label="二级学院" prop="data" header-align="center">
        <div v-for="(data,key) in this.tableHeader" :key="key">
          <el-table-column
            v-if="data !== undefined"
            :label="data"
            width="150"
            header-align="center"
          >
            <template slot-scope="scope">
              <div class="jinyong">
                <el-input
                  class="nolineInput"
                  size="small"
                  @focus="editThis(scope,key)"
                  v-model="scope.row[key]"
                  placeholder="0"
                  @keypress.enter.native="inputBlur"
                  @blur="changeData(scope.row[key],scope,key)"
                  :disabled="!ifreview"
                ></el-input>
              </div>
            </template>
          </el-table-column>
        </div>
      </el-table-column>
    </el-table>
    <el-button
      type="warning"
      v-if="ifreview"
      @click="dialogVisible=true"
      style="float: right; margin:2vh 16vh;"
    >提交</el-button>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span>确认提交之后将不可修改，确认提交？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitData">确 定</el-button>
      </span>
    </el-dialog>
  </el-main>
</template>

<script>
export default {
  name: "responsibilityData.vue",

  components: {},
  data() {
    return {
      dialogVisible: false,
      id: 0,
      responseible: 1,
      isLoading: true,
      editRow: -1,
      editCol: -1,
      tempData: "",
      tableData: [],
      collegeData: [],
      indexData: [],
      tableHeader: [],
      formedData: [],
      ifreview: false
    };
  },
  methods: {
    /**
     *  通过id对应index
     *  @param isKey 为true返回key，为false返回元素
     */
    findInArrById(ele, arr, isKey) {
      for (let key in arr) {
        if (ele == arr[key].id) {
          if (isKey) {
            return key;
          } else {
            return arr[key];
          }
        }
      }
      return -1;
    },

    findInArrByName(ele, arr, isKey) {
      for (let key in arr) {
        if (ele == arr[key].unit) {
          if (isKey) {
            return key;
          } else {
            return arr[key];
          }
        }
      }
      return -1;
    },

    /**
     * 从后台获取学院id表，然后再从数据中进行匹配
     */
    getCollegeData() {
      let $this = this;
      this.$http({
        method: "get",
        url: "/api/mender/getAllCollegeIdAndName"
        // params: {
        //     id: this.id
        // }
      })
        .then(function(response) {
          //返回0则表示成功
          if (response.data.code == 0) {
            //可能会有问题

            $this.collegeData = response.data.data;
            $this.tableHeader = $this.getHeader($this.tableData);
            $this.getIndexData();
          } else {
            $this.message(true, response.data.message, "danger");
          }
        })
        .catch(error => console.log(error));
    },

    /**
     *  获取指标数组
     */
    getIndexData() {
      let $this = this;
      $this
        .$http({
          method: "get",
          url: "/api/mender/getIndexUnitMender",
          params: {
            // responseible: 1
          }
        })
        .then(function(response) {
          //返回0则表示成功
          if (response.data.code === 0) {
            //可能会有问题
            $this.indexData = response.data.data;
            console.log("collegeData");
            console.log($this.collegeData);
            console.log("tableHeader");
            console.log($this.tableHeader);
            console.log("indexData");
            
            console.log($this.indexData);
            
            $this.handleTableData();
          } else {
            $this.message(true, response.data.message, "danger");
          }
        })
        .catch(error => console.log(error));
    },

    /**
     *  从数据中对照关系表获取学院的排序数组，然后用做table表头
     * @param arr 数据数组
     * @returns {Array} 排好序的表头数组
     */
    getHeader(arr) {
      let header = [];
      //第一条数据的指标的内容
      //不再从第一条数据开始获取
      // let target = arr[0]['1'];
      // for (let key in target) {
      //     for (let num in target[key]) {
      //         let headIndex = this.findInArrById(num, this.collegeData, true);
      //         console.log(headIndex + ".." + this.collegeData[headIndex].name)
      //         if (headIndex !== -1) {
      //             header[num] = this.collegeData[headIndex].name;
      //         } else {
      //             this.message(true, "数据发生错误", "warning");
      //             return [];
      //         }
      //
      //     }
      //
      // }

      for (let item of this.collegeData) {
        header[item.id] = item.name;
      }
      return header;
    },

    /**
     * 把从后台获取到的数据进行格式化放入表格中
     * @returns {Array}
     */
    handleTableData() {
      let $this = this;
      // $this.getIndexData();
      this.$http({
        method: "get",
        url: "/api/mender/getCollegeDutyData"
        // params: {
        //     //此处还差处理如果传来了id怎么跳转指定记录
        //     year:this.$route.query.year,
        //     responseible: this.responseible
        // }
      })
        .then(function(response) {
          //返回0则表示成功
          if (response.data.code == 0) {
            //如果之前有数据
            $this.ifreview =
              response.data.data.review == 2 || response.data.data.review == 0
                ? false
                : true;
            $this.id = response.data.data.id;
            $this.tableData = JSON.parse(response.data.data.content);
            let data = [];
            for (let bigIndex in $this.tableData) {
              for (let index in $this.tableData[bigIndex]) {
                let row = {};
                row.index = $this.findInArrById(
                  parseInt(index),
                  $this.indexData,
                  false
                ).unit;
                for (let cell in $this.tableData[bigIndex]) {
                  for (let item of $this.tableData[bigIndex][cell]) {
                    for (let innerKey in item) {
                      row[innerKey] = item[innerKey];
                    }
                  }
                }
                data.push(row);
              }
            }
            $this.isLoading = false;
            $this.formedData = data;
          } else if (response.data.code == 1) {
            //如果之前没有数据，根据表头创建
            $this.ifreview = true;
            let data = [];
            for (let index of $this.indexData) {
              let row = {};
              // row.index = $this.findInArrById((parseInt(index) + 1), $this.indexData, false).unit;
              row.index = index.unit;
              for (let head in $this.tableHeader) {
                row[head] = 0;
              }
              data.push(row);
            }
            $this.formedData = data;
            $this.isLoading = false;
          } else {
            $this.message(true, response.data.message, "danger");
          }
        })
        .catch(error => console.log(error));
    },

    /**
     * 双击某一格的数据进行修改
     * @param scope 当前行
     * @param col 当前列
     */
    editThis(scope, col) {
      this.editRow = scope.$index;
      this.editCol = col;
      // this.$refs[scope.$index + col].focus();
      //先把之前的数据缓存下来
      this.tempData = scope.row[col];
    },

    /**
     * 输入数据之后，失去焦点，临时保存到数据库
     */
    changeData(data, scope, key) {
      let _this = this;
      //判断数据是否合格或发生改变
      if (!_this.ifreview) {
        _this.message(
          true,
          "您的数据正在审核或者已经通过，无法进行操作",
          "warning"
        );
        return;
      }

      if (data == this.tempData) {
        //数据没变按回车什么都不做
      } else if (
        data == "" ||
        (!/^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$/.test(data) &&
          !/^(0|[1-9][0-9]*)$/.test(data))
      ) {
        //撤回上一步操作
        scope.row[key] = this.tempData;
        _this.message(true, "请输入合法的数据格式！" + data, "warning");
      } else {
        let changedData = JSON.stringify(this.dataReform());
        //请求保存
        let $this = this;
        this.$axios(
          "post",
          "/api/mender/updatecollegeDutyData",
          {
            // responseible: this.responseible,
            // id: $this.id,
            content: changedData
          },
          function(res) {
            if (res.data.code == 2) {
              $this.id = response.data.result;
            }
          }
        );
      }
      this.inputBlur();
    },
    /**
     * 把表格数据转回JSON
     */
    dataReform() {
      let reform = [];
      for (let ele in this.formedData) {
        let now = {};
        let arr = [];
        for (let index in this.formedData[ele]) {
          if (index === "index") {
            continue;
          }
          let obj = {};
          obj[index] = this.formedData[ele][index];
          arr.push(obj);
        }
        let unitID = this.findInArrByName(
          this.formedData[ele].index,
          this.indexData,
          false
        ).id;
        now[unitID] = arr;
        reform.push(now);
      }
      return reform;
    },
    inputBlur() {
      //此处应该提交数据 处理数据，然后恢复原始状态
      this.editRow = -1;
      this.editCol = -1;
    },

    /**
     * 点击提交数据，数据提交至数据库
     */
    commitData() {
      let $this = this;
      let changedData = JSON.stringify($this.dataReform());
      $this.$axios(
        "post",
        "/api/mender/commitDutyData",
        {
          content: changedData
        },
        function(res) {
          $this.ifreview = false;
          $this.dialogVisible = false;
        }
      );
    }
  },
  mounted() {
    //外部跳转
    let _this = this;
    _this.id = this.$route.query.id;

    //生成表头
    _this.getCollegeData();
  }
};
</script>

<style>
.nolineInput input {
  outline: none;
  border: none !important;
  background-color: transparent;
}

.nolineInput input:hover {
  background-color: white;
}

.nolineInput input:focus {
  background-color: white;
}

.jinyong .el-input.is-disabled .el-input__inner {
  background-color: #ffffff !important;
  border-color: #e4e7ed;
  color: #0c0c0c !important;
  cursor: not-allowed;
}

body .el-table th.gutter{
    display: table-cell!important;
}
</style>